package com.realm;

import com.pojo.SysUsers;
import com.service.MenuService;
import com.service.RoleService;
import com.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.Set;

public class MyUserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    @Autowired
    RoleService roleService;

    @Autowired
    MenuService menuService;

    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        SysUsers user = (SysUsers) principals.getPrimaryPrincipal();

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        Set<String> roles = roleService.findRolesByUserId(user.getId());

        authorizationInfo.setRoles(roles);

        Set<String> perms = menuService.findPermsByUserId(user.getId());

        authorizationInfo.setStringPermissions(perms);

        return authorizationInfo;
    }

    /**
     * 认证：根据用户名和密码 进行校验
     *  获取用户输入的用户名和密码
     *  根据用户名和密码在数据库进行查询
     *  如果能查询到，说明登录成功
     * @param token
     * @return
     * @throws
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户输入的用户名和密码
        String username = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new RuntimeException("用户名或密码为空");
        }
        // 根据用户名在数据库进行查询
        SysUsers user = userService.findByUsername(username);
        if(user == null) {
            //如果user为空，说明此用户不存在
            throw new UnknownAccountException("用户不存在");
        }

        //判断用户的状态是否是可用的
        if(user.getStatus() == 0) {
            throw new LockedAccountException("账户已锁定");
        }
        //数据库中的密码
        String pwd = user.getPassword();
        if(!password.equalsIgnoreCase(pwd)) {
            throw new CredentialsException("密码错误");
        }

        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), user.getRealname());

        return authenticationInfo;
    }
}